// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import vueResource from 'vue-resource'
import CryptoJS from 'crypto-js'
import App from './app.vue'
import router from './router'
import store from './vuex/store.js'
import '../common/fonts/iconfont.css'
import preview from 'vue-photo-preview'
import 'vue-photo-preview/dist/skin.css'

// import router from './router'
Vue.use(vueResource)
Vue.use(ElementUI)
Vue.config.productionTip = false
Vue.use(preview)

Vue.prototype.encrypt = function (obj) {
  var key = CryptoJS.enc.Utf8.parse('1234567812345678')
  var srcs = CryptoJS.enc.Utf8.parse(JSON.stringify(obj))
  var encrypted = CryptoJS.AES.encrypt(srcs, key, {mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7})
  return encrypted.toString()
}
Vue.prototype.decode = function (obj) {
  var key = CryptoJS.enc.Utf8.parse('1234567812345678')
  var decrypt = CryptoJS.AES.decrypt(obj, key, {mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7})
  return CryptoJS.enc.Utf8.stringify(decrypt).toString()
}
Vue.prototype.$ajax = {
  get: function (url, fn) {
    // XMLHttpRequest对象用于在后台与服务器交换数据
    var xhr = new XMLHttpRequest();
    xhr.open('GET', "https://hdzmsspt.com/" + url, true);
    xhr.onreadystatechange = function () {
      // readyState == 4说明请求已完成
      if (xhr.readyState == 4 && xhr.status == 200 || xhr.status == 304) {
        // 从服务器获得数据
        fn.call(this, xhr.responseText);
      }
    };
    xhr.send();
  },
  // datat应为'a=a1&b=b1'这种字符串格式，在jq里如果data为对象会自动将对象转成这种字符串格式
  post: function (url, data, fn) {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "https://hdzmsspt.com/" + url, true);
    // 添加http头，发送信息至服务器时内容编码类型
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.onreadystatechange = function () {
      if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {
        fn.call(this, xhr.responseText);
      }
    };
    xhr.send(data);
  }
}
Vue.http.interceptors.push(function (request, next) {
  request.body = this.encrypt(request.body)
  next((response) => {
    if (!response.body) return {}
    response.body = JSON.parse(this.decode(response.body))
    return response
  })
})
router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    sessionStorage.removeItem('user')
  }
  let user = JSON.parse(sessionStorage.getItem('user'))
  if (!user && to.path !== '/login') {
    next({ path: '/login' })
  } else if (user && to.path === '/') {
    next({name: 'survey', params: {orignflag: 1}})
  } else {
    next()
  }
})

/* eslint-disable no-new */
new Vue({
  el: '#app',
  // router,
  store,
  router,
  template: '<App/>',
  components: { App }
})
